package com.cheng.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheng.service.FaceService.AuthService;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/face")
public class FaceController {
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisUtil redisUtil;
    public static final String FACE_TOKEN = "FACE_TOKEN";
    public static final long TIME_OUT =  2592000;
    //人脸最低分数
    public static final int MINSCORE =  70;

    private static final Logger logger = LoggerFactory.getLogger(FaceController.class);

    public FaceController(){
        super();
    }


    public String getFaceToken(){
        JSONObject obj = new JSONObject();
        redisUtil.get(FACE_TOKEN);
        //���������û��token�����ýӿ�ȥ���
        String token = (String) redisUtil.get(FACE_TOKEN);
        if(Utils.isBlank(token)){
            token = authService.getAuth();
            redisUtil.set(FACE_TOKEN,authService.getAuth(),TIME_OUT);
            return token;
        }
        return token;
    }
    @RequestMapping(value = "/addFace" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject addFace(HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //接受前台的base64图片编码
        String base64 = request.getParameter("base64");
        //获得百度云token
        String accessToken = getFaceToken();
        //调用人脸接口，添加人脸
        JSONObject json = new JSONObject();
        json.put("image",base64);
        json.put("image_type","BASE64");
        json.put("max_face_num",5);
        logger.info("=============人脸调用检测接口开始=============");

        //前台传入的人脸数大于1,提示用户重新上传
        JSONObject faceDetect = JSON.parseObject(authService.faceDetect(json,accessToken));
        JSONObject result = faceDetect.getJSONObject("result");
        if(result == null){
            //没有检测到人脸的处理
            return setReturnObjInfo("noHasFace","没有检测到人脸");
        }
        //得到人脸数量
        String faceNum = result.getString("face_num");
        if(!faceNum.equals("1")){
            //检测到人脸数量大于1
            return setReturnObjInfo("max_face_num","上传的照片人脸数量大于1");
        }

        json.remove("max_face_num");
        logger.info("=============人脸调用注册接口开始=============");

        //获得返回接口的信息
        json.put("group_id", "group_repeat");
        json.put("user_id", "user2");
        json.put("user_info", "abcd");
        json.put("liveness_control", "NORMAL");
        json.put("quality_control", "LOW");
        JSONObject addFace = JSON.parseObject(authService.addFace(json,accessToken));

        JSONObject addFaceJSONObject = addFace.getJSONObject("result");

        String userFaceToken = addFaceJSONObject.getString("face_token");

        returnObj.put("info",addFace);
        returnObj.put("resCode","100");
        returnObj.put("resInfo","suc");
        return returnObj;
    }


    @RequestMapping(value = "/matchFace" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject matchFace(HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //获取前台用户拍照的base64编码
        String base64 = request.getParameter("base64");
        //获得百度云token
        String accessToken = getFaceToken();
        //调用人脸接口，添加人脸
        JSONObject matchJson = new JSONObject();
        //todo：用户之前注册的face_token 数据库
        String faceToken = "cbd132cc2feb9408faab596741853a5e";

        //传入参数组装
        JSONArray match = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("image",faceToken);
        json.put("image_type","FACE_TOKEN");
        json.put("face_type","LIVE");
        json.put("quality_control","NORMAL");
        json.put("liveness_control","NORMAL");
        match.add(json);


        JSONObject json1 = new JSONObject();
        json1.put("image",base64);
        json1.put("image_type","BASE64");
        json1.put("face_type","LIVE");
        json1.put("quality_control","NORMAL");
        json1.put("liveness_control","NORMAL");
        match.add(json1);


        JSONObject matchFace = JSON.parseObject(authService.faceMatch(match,accessToken));

        JSONObject matchFaceJSONObject = matchFace.getJSONObject("result");

       if(matchFaceJSONObject == null){
          return  setReturnObjInfo("-100","质量检测不通过，请重新上传");
       }
       String score = matchFaceJSONObject.getString("score");
       //判断人脸是否为一张脸
        if(Double.parseDouble(score)<=MINSCORE){
            return setReturnObjInfo("noMatch","人脸检测失败，请重新上传");
        }

        returnObj.put("info",matchFace);
        return returnObj;
    }


    public static JSONObject setReturnObjInfo(String resCode, String resInfo) {
        JSONObject result = new JSONObject();
        result.put("resCode",resCode);
        result.put("resInfo",resInfo);
        return result;
    }
}
